package com.example.t470p.facechecktickets.PictureFaceMatch;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.t470p.facechecktickets.R;
import com.example.t470p.facechecktickets.PictureFaceMatch.camare.CameraPreview;
import com.example.t470p.facechecktickets.PictureFaceMatch.camare.FocusView;
import com.example.t470p.facechecktickets.Utils.util;
import com.example.t470p.facechecktickets.facesdk.FaceHandle;
import com.example.t470p.facechecktickets.facesdk.IFaceSDK;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class TakePhotoActivity extends Activity implements CameraPreview.OnCameraStatusListener,
        SensorEventListener {
    private static final String TAG = "TakePhoteActivity";
    CameraPreview mCameraPreview;
    RelativeLayout mTakePhotoLayout;
    LinearLayout mCropperLayout;
    public static byte img[];
    TextView hint_tv;
    Bitmap idcardPhoto;
    Bitmap presentPhoto;

    ImageView ivIdcardPhoto;
    ImageView ivPresentPhoto;
    final static float VERIFY_THRESHOLD = 75;
    SoundPool soundPool;
    IFaceSDK iFaceSDK;
    private Object idcardPhotofeaObj;


    /************************karl add 2019-01-11*************************/
    private String  ResultMsg="FAIL";
    private int m_WorkMode;         //1:对比 2:采集
    Bitmap m_CollectPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_take_photo);
        mCameraPreview = (CameraPreview) findViewById(R.id.cameraPreview);
        FocusView focusView = (FocusView) findViewById(R.id.view_focus);
        mTakePhotoLayout = (RelativeLayout) findViewById(R.id.take_photo_layout);
        mCropperLayout = (LinearLayout) findViewById(R.id.cropper_layout);
        ivIdcardPhoto=(ImageView)findViewById(R.id.ivIdcardPhoto);
        ivPresentPhoto=(ImageView)findViewById(R.id.ivPresentPhoto);
        mCameraPreview.setFocusView(focusView);
        mCameraPreview.setOnCameraStatusListener(this);
        mSensorManager = (SensorManager) getSystemService(Context.
                SENSOR_SERVICE);
        mAccel = mSensorManager.getDefaultSensor(Sensor.
                TYPE_ACCELEROMETER);

        hint_tv = (TextView) findViewById(R.id.hint);
        soundPool= new SoundPool(10, AudioManager.STREAM_SYSTEM,5);
        soundPool.load(this,R.raw.hycg,1);
        soundPool.load(this,R.raw.hysb,1);

        Intent intent = getIntent();
        byte[] imgBytes = intent.getByteArrayExtra("img_byte");
        int ALGORITHM_VERSION=intent.getIntExtra("ALGORITHM_VERSION",2);
        m_WorkMode = intent.getIntExtra("WORKINGMODE",1);
        if(1 == m_WorkMode)
        {
            iFaceSDK=FaceHandle.getFaceSDKInstance(ALGORITHM_VERSION);
            if (img != null) {
                idcardPhoto = BitmapFactory.decodeByteArray(img, 0, img.length);
                ivIdcardPhoto.setImageBitmap(idcardPhoto);
                hint_tv.setText("请对准人脸拍照核验");
                idcardPhotofeaObj=null;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        idcardPhotofeaObj=iFaceSDK.getIDCardPhotoFeature(idcardPhoto);
                    }
                }).start();

            }
        }else{
            hint_tv.setText("请对准人脸拍照采集");
        }

    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccel, SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

    @Override
    protected void onDestroy() {
        soundPool.release();
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.e(TAG, "onConfigurationChanged");
        super.onConfigurationChanged(newConfig);
    }

    public void takePhoto(View view) {
        if(mCameraPreview != null) {
            mCameraPreview.takePicture();
        }
    }

    public void openlight(View view)
    {
        if (mCameraPreview != null)
        {
            mCameraPreview.openLight();
            view.setVisibility(View.GONE);
            View v = findViewById(R.id.nolight);
            v.setVisibility(View.VISIBLE);
        }
    }
    public void offlight(View v)
    {
        if (mCameraPreview != null)
        {
            mCameraPreview.offLight();
            v.setVisibility(View.GONE);
            View view = findViewById(R.id.light);
            view.setVisibility(View.VISIBLE);
        }
    }
    public void close(View view) {
        ResultMsg = "COLLECTFAIL";
        Intent intent	= new Intent();
        intent.putExtra("result", ResultMsg);
        //请求代码可以自己设置
        setResult(RESULT_OK, intent);
        finish();
    }


    /**
     * 拍照成功后回调
     * 存储图片并显示截图界面
     * @param data
     */
    @Override
    public void onCameraStopped(byte[] data) {
        Log.i("TAG", "==onCameraStopped==");
        if(1 == m_WorkMode)
        {
            new VerifyAsyncTask(data).execute();
        }else if(2 == m_WorkMode)
        {
            new SnapshotAsyncTask(data).execute();
        }
    }

    //抓拍任务
    private class SnapshotAsyncTask extends AsyncTask<Void,Void,Integer>{
        byte[] data;
        private ProgressDialog dialog = null;
        public SnapshotAsyncTask(byte[] data) {
            this.data = data;
        }

        @Override
        protected void onPreExecute() {
            //解析图片
            m_CollectPhoto=BitmapFactory.decodeByteArray(data, 0, data.length);//getBitmapFromData(data);
            //显示图片
            ivPresentPhoto.setImageBitmap(m_CollectPhoto);
            //保存图片
            saveBitmap(m_CollectPhoto,getSDPath(),"/UpdateImg.jpg");
            ResultMsg = "COLLECTSUCCESS";
        }

        @Override
        protected Integer doInBackground(Void... params) {
            return 0;
        }

        @Override
        protected void onPostExecute(Integer score) {
            mCameraPreview.start();
/*            new AlertDialog.Builder(TakePhotoActivity.this)
                    .setTitle("抓拍结果")
                    .setMessage("抓拍成功")
                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //退出当前Activity
                            MyClose(ResultMsg);
                        }
                    }).setCancelable(false).show();*/
            MyClose(ResultMsg);

            super.onPostExecute(score);
        }
    }


    private class VerifyAsyncTask extends AsyncTask<Void,Void,Integer>{
        byte[] data;
        private ProgressDialog dialog = null;
        public VerifyAsyncTask(byte[] data) {
            this.data = data;
        }

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(TakePhotoActivity.this, "", "正在核验，请稍等", true);
            super.onPreExecute();
            presentPhoto=BitmapFactory.decodeByteArray(data, 0, data.length);//getBitmapFromData(data);
            ivPresentPhoto.setImageBitmap(presentPhoto);
        }

        @Override
        protected Integer doInBackground(Void... params) {
            if(idcardPhotofeaObj==null)
                idcardPhotofeaObj=iFaceSDK.getIDCardPhotoFeature(idcardPhoto);
            if(idcardPhotofeaObj==null) return 0;
            Object presentPhotoFeaObj=iFaceSDK.getPresentPhotoFeature(presentPhoto);
            return iFaceSDK.compareFeature(idcardPhotofeaObj,presentPhotoFeaObj);
        }

        @Override
        protected void onPostExecute(Integer score) {
            mCameraPreview.start();
            dialog.dismiss();
            checkScore(score);
            super.onPostExecute(score);
        }
    }


    private void checkScore(final int score) {
        String msg = "核验失败";
        if (score>=VERIFY_THRESHOLD) {
            msg = "核验成功";
            ResultMsg="COMPARESUCCESS";
            //setResult(RESULT_OK);
            soundPool.play(1,1, 1, 0, 0, 1);
        }else{
            ResultMsg="FAIL";
            soundPool.play(2,1, 1, 0, 0, 1);
        }

        new AlertDialog.Builder(TakePhotoActivity.this)
                .setTitle("对比结果")
                .setMessage(msg)
                .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //退出当前Activity
                        MyClose(ResultMsg);
                    }
                }).setCancelable(false).show();
    }


    private float mLastX = 0;
    private float mLastY = 0;
    private float mLastZ = 0;
    private boolean mInitialized = false;
    private SensorManager mSensorManager;
    private Sensor mAccel;
    @Override
    public void onSensorChanged(SensorEvent event) {

        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
        if (!mInitialized){
            mLastX = x;
            mLastY = y;
            mLastZ = z;
            mInitialized = true;
        }
        float deltaX  = Math.abs(mLastX - x);
        float deltaY = Math.abs(mLastY - y);
        float deltaZ = Math.abs(mLastZ - z);

        if(deltaX > 0.8 || deltaY > 0.8 || deltaZ > 0.8){
            mCameraPreview.setFocus();
        }
        mLastX = x;
        mLastY = y;
        mLastZ = z;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
    /*****************************karl add 2018-12-27***************************/
    /*
    * 退出Activity
     */
    private void MyClose(String Msg)
    {
        Intent intent	= new Intent();
        intent.putExtra("result", Msg);
        //请求代码可以自己设置
        setResult(RESULT_OK, intent);
        finish();
    }

    /*
    * 获取SD卡路径
    */
    public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if(sdCardExist)
        {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    /*
    * Bitmap保存成图片
    */
    private void saveBitmap(Bitmap bitmap,String path, String filename)
    {
        File file = new File(path + filename);
        if(file.exists()){
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 10, out)) {
                out.flush();
                out.close();
            }
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}